//
//  ExamRegistrationManager.m
//  FH2go
//
//  Created by Hannes Feichtl on 11.04.13.
//  Copyright (c) 2013 Hannes Feichtl. All rights reserved.
//

#import "ExamRegistrationManager.h"
#import "TouchXML.h"


@implementation ExamRegistrationManager

@synthesize queue = _queue;

- (id)init{
    self = [super init];
    if (self) {
        _queue = [[NSOperationQueue alloc] init];
        
        // A maximum of concurrent operations
        [_queue setMaxConcurrentOperationCount:4];
    }
    return self;
}

-(void)registerExam:(Exam*)exam withHandler:(void(^)(NSError *error)) completion{

    // Get username and password from settings manager
    NSString *username = [[SettingsManager sharedInstance] username];
    NSString *password = [[SettingsManager sharedInstance] password];
    NSString *type;

    
    if([exam.status isEqual:@"registered"]) {
        type=@"signoff";
    } else {
        type=@"signup";
    }
    
    // create URL string with username and password included
    NSString *requestString = [NSString stringWithFormat:@"https://ws.fh-joanneum.at/signup.php?u=%@&p=%@&k=LOvkZCPesk&a=%@&e=%@",username,password,type,exam.identifier];
    
    
    
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestString]
                                                  cachePolicy:0
                                              timeoutInterval:30];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:_queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        
        //If the request returned an error
        if (error) {
            /*
             execute completion block on main thread
             */
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(error);
                
            });
        } else {
            // Array to hold the returned data
            
            // Create a XMLDocument from the returned data
            CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithData:data encoding:NSUTF8StringEncoding options:0 error:nil];
            
            // Checks if the request was succesfull by looking at the Status returned
            if(![[[xmlDoc nodeForXPath:@"//Status" error:nil] stringValue] isEqualToString:@"OK"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // Create error
                    NSString *status = [NSString stringWithFormat:@"Something went wrong %@",[[xmlDoc nodeForXPath:@"//Status" error:nil] stringValue]];
                    NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
                    [errorDetail setValue:status forKey:NSLocalizedDescriptionKey];
                    NSError *error = [NSError errorWithDomain:@"None" code:100 userInfo:errorDetail];
                    // run completion block with error
                    completion(error);
                });
                // No need to continue parsing when server returns bad status. Return method!
                return;
            }
                        
            /*
             will be executed on the main thread again
             dispatch_get_main_queue() -> C function will return the main queue
             */
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(nil);
                
            });
        }
    }];

}

@end
